<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        body {
            overflow: hidden;
        }

        .box {
            width: 150px;
            height: 150px;
            background-color: #6ff;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</body>

<script>

    // var box = document.querySelector(".box");
    // document.onmousemove = function (evt) {
    //     var e = evt || window.event;

    //     var x = e.pageX + 20;
    //     var y = e.pageY + 20;

    //     box.style.left = x + "px";
    //     box.style.top = y + "px";

    // }
    var boxList = document.querySelectorAll(".box");


    for (var i = 0; i < boxList.length; i++) {
        var box = boxList[i];
        box.onmousedown = function (evt) {
            var e = evt || window.event;
            var posX = e.offsetX;
            var posY = e.offsetY;
            console.log(posX, posY);
            var maxWidth = document.documentElement.clientWidth - this.clientWidth;
            var maxHeight = document.documentElement.clientHeight - this.clientHeight;

            var _this = this;   //把this  赋值给一个变量 _this  
            document.onmousemove = function (evt) {
                // 此事件中  this指向document
                var e = evt || window.event;
                var x = evt.pageX - posX;
                var y = evt.pageY - posY;

                if (x < 0) {
                    x = 0;
                }
                if (x > maxWidth) {
                    x = maxWidth;
                }
                if (y < 0) {
                    y = 0;
                }
                if (y > maxHeight) {
                    y = maxHeight;
                }

                _this.style.left = x + "px";
                _this.style.top = y + "px";
            }

        }

        document.onmouseup = function () {
            document.onmousemove = null;
        }
    }
</script>

</html>